package com.sdy.supermarket.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.BizException;
import com.sdy.common.model.PageQuery;
import com.sdy.common.model.PageResult;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.mvc.controller.BaseController;
import com.sdy.mvc.utils.JsonUtil;
import com.sdy.supermarket.biz.model.GsRes;
import com.sdy.supermarket.biz.model.GsUserRes;
import com.sdy.supermarket.biz.service.GsResService;
import com.sdy.supermarket.biz.service.GsUserResService;
import com.sdy.supermarket.biz.vo.UserResListVo;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.DeptDto;
import com.sdy.usercenter.api.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Executable;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户资源
 * </p>
 *
 * @author zzq
 * @since 2019-07-24
 */
@Slf4j
@RestController
@SuppressWarnings("unchecked")
@RequestMapping("/gsUserRes")
public class GsUserResController extends BaseController {
    @Autowired
    private GsUserResService gsUserResService;
    @Autowired
    private GsResService gsResService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private UserQueryApi queryApi;

    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    /**
     * 获取当前登录用户所拥有的资源列表
     *
     * @return
     */
    @GetMapping("/getUserResList")
    public Response getUserResList(Page<GsRes> page, String resName, Integer state, HttpServletRequest request) throws BizException, UnsupportedEncodingException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "未登录");
        resName = URLDecoder.decode(resName, "UTF-8");
        IPage<GsRes> userResList = gsUserResService.getUserResList(page, userInfo.getUserId(), resName, state);
        return Response.success(userResList);
    }

    /**
     * 点击授权管理后查询当前用户所在部门的用户列表
     *
     * @param page size current
     * @return
     * @throws BizException
     */
    @GetMapping("/getDeptPerList")
    public Response getDeptPerList(Page page, Integer deptId, Integer resId, String userName) throws BizException, UnsupportedEncodingException {
        userName = URLDecoder.decode(userName, "UTF-8");
        PageQuery pageQuery = new PageQuery(page.getCurrent(), page.getSize());
        pageQuery.setCurrent(page.getCurrent());
        pageQuery.setSize(page.getSize());
        PageResult<UserDTO> pageResult = queryApi.pageUserInDept(pageQuery, deptId, userName, false);
        PageResult<UserResListVo> userPage = JsonUtil.convertPage2(pageResult, UserResListVo.class);
        // 给所有用户设置是否拥有资源
        userPage.getRecords().forEach(user -> user.setIsHave(0));
        // 根据查询到的用户id查询user_res表,然后根据查询到的数据给isHave字段赋值
        userPage.setRecords(setUserIsHaveRes(userPage.getRecords(), resId));
        return Response.success(userPage);
    }

    /**
     * 给某个用户授权或者取消授权
     *
     * @param map userId resId
     * @return
     */
    @PostMapping("/isApproveRes")
    public Response isApproveRes(@RequestBody Map<String, Object> map) {
        int approveRes = gsUserResService.isApproveRes((Integer) map.get("userId"), (Integer) map.get("resId"));
        return approveRes != 0 ? Response.success() : Response.error();
    }

    /**
     * 一键给该部门所有人员授权&取消授权
     *
     * @param map deptId resId userName type
     * @return
     */
    @PostMapping("/oneKeyApproveRes")
    public Response oneKeyApproveRes(@RequestBody Map<String, Object> map) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    int oneKeyApproveRes = gsUserResService.oneKeyApproveRes((Integer) map.get("deptId"), (Integer) map.get("resId"), (String) map.get("userName"), (Integer) map.get("type"));
                } catch (BizException e) {
                    log.error("GsUserResServiceImpl(一键授权)-批量授权时出现错误" + e);
                }
            }
        });
        return Response.success("由于数据量较大,请稍后查看");
    }

    /**
     * 根据当前用户获取该用户所管理的部门以及子部门
     *
     * @return
     */
    @GetMapping("/getDeptList")
    public Response getDeptListByUserId(HttpServletRequest request, Integer parentId) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "未登录");
        List<DeptDto> deptDtos = queryApi.listUserManageDept(userInfo.getUserId(), parentId);
        return Response.success(deptDtos);
    }

    /**
     * 根据传入的用户列表查询用户资源表判断该用户是否拥有该资源权限，在返回的列表中isHave参数显示
     *
     * @param list
     * @param resId
     * @return
     */
    private List<UserResListVo> setUserIsHaveRes(List<UserResListVo> list, Integer resId) {
        if (list.isEmpty()) {
            return list;
        }
        List<GsUserRes> userResList = gsUserResService.list(Wrappers.<GsUserRes>lambdaQuery().in(GsUserRes::getUserId,
                list.stream().map(user -> user.getId()).collect(Collectors.toList())).eq(GsUserRes::getResId, resId));
        userResList.forEach(userRes -> {
            list.forEach(user -> {
                if (userRes.getUserId().equals(user.getId())) {
                    user.setIsHave(1);
                }
            });
        });
        return list;
    }

}
